package cn.edu.zut.qixiang.mock;

import java.sql.*;
import java.util.Random;

/**
 * 采集站数据生成工具类
 * 每个地区(district_id 1-12)生成18个采集站，6种类型每种3个
 * @author 86178
 */
public class CollectionStationsDataGenerator {

    // 采集站类型枚举
    private static final String[] STATION_TYPES = {
            "空气数据采集站", "水文数据采集站", "气压数据采集站",
            "温度数据采集站", "辐射数据采集站", "风况数据采集站"
    };

    // 采集站名称前缀
    private static final String[] STATION_NAME_PREFIXES = {
            "中心", "东区", "西区", "南区", "北区", "新区", "老区", "一号", "二号", "三号"
    };

    public static void main(String[] args) {
        // 数据库配置
        String url = "jdbc:mysql://localhost:3306/qixiang_base?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
        String user = "root";
        String password = "520521fcf..@1234";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            // 生成采集站数据
            generateCollectionStations(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成采集站数据
     */
    public static void generateCollectionStations(Connection conn) {
        String selectDistrictsSql = "SELECT district_id, district_name, longitude, latitude FROM districts ORDER BY district_id";
        String insertStationSql = "INSERT INTO collection_stations (station_id, district_id, station_name, longitude, latitude, station_type) VALUES (?, ?, ?, ?, ?, ?)";

        try (PreparedStatement selectStmt = conn.prepareStatement(selectDistrictsSql);
             PreparedStatement insertStmt = conn.prepareStatement(insertStationSql)) {

            conn.setAutoCommit(false);
            Random random = new Random();

            // 获取所有地区信息
            ResultSet districtRs = selectStmt.executeQuery();

            int stationId = 1; // 采集站ID从1开始
            int batchSize = 50;
            int count = 0;

            while (districtRs.next()) {
                int districtId = districtRs.getInt("district_id");
                String districtName = districtRs.getString("district_name");
                double baseLongitude = districtRs.getDouble("longitude");
                double baseLatitude = districtRs.getDouble("latitude");

                System.out.println("正在生成地区 " + districtName + " 的采集站数据...");

                // 每个地区生成18个采集站（6种类型 × 每种3个）
                for (String stationType : STATION_TYPES) {
                    for (int i = 1; i <= 3; i++) {
                        // 生成采集站名称
                        String stationName = generateStationName(districtName, stationType, i);

                        // 在基准经纬度基础上生成随机偏移（0.01-0.03度，约1-3公里）
                        double longitude = baseLongitude + (random.nextDouble() * 0.02 - 0.01);
                        double latitude = baseLatitude + (random.nextDouble() * 0.02 - 0.01);

                        // 设置插入参数
                        insertStmt.setInt(1, stationId);
                        insertStmt.setInt(2, districtId);
                        insertStmt.setString(3, stationName);
                        insertStmt.setDouble(4, longitude);
                        insertStmt.setDouble(5, latitude);
                        insertStmt.setString(6, stationType);

                        insertStmt.addBatch();
                        stationId++;
                        count++;

                        // 批量提交
                        if (count % batchSize == 0) {
                            insertStmt.executeBatch();
                            conn.commit();
                        }
                    }
                }
            }

            // 提交剩余数据
            insertStmt.executeBatch();
            conn.commit();

            System.out.println("采集站数据生成完成！共生成 " + count + " 个采集站。");
            System.out.println("每个地区生成 " + (STATION_TYPES.length * 3) + " 个采集站。");

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 生成采集站名称
     */
    private static String generateStationName(String districtName, String stationType, int index) {
        Random random = new Random();
        String typeSuffix = stationType.replace("数据采集站", "");

        // 名称格式：地区 + 方位/编号 + 类型 + "监测站"
        String[] numberSuffixes = {"一", "二", "三", "1", "2", "3"};
        String[] directionSuffixes = {"东", "西", "南", "北", "中"};

        String middlePart;
        if (index <= 3) {
            middlePart = directionSuffixes[index - 1];
        } else {
            middlePart = numberSuffixes[random.nextInt(numberSuffixes.length)];
        }

        return districtName + middlePart + typeSuffix + "监测站";
    }

    /**
     * 生成更详细的采集站数据（包含更多信息）
     */
    public static void generateDetailedCollectionStations(Connection conn) {
        String selectDistrictsSql = "SELECT district_id, district_name, longitude, latitude FROM districts ORDER BY district_id";
        String insertStationSql = "INSERT INTO collection_stations (station_id, district_id, station_name, longitude, latitude, station_type) VALUES (?, ?, ?, ?, ?, ?)";

        // 详细的采集站名称映射
        String[][] detailedStationNames = {
                // 空气数据采集站
                {"空气质量监测中心站", "大气成分观测站", "环境空气质量站"},
                // 水文数据采集站
                {"降水量监测站", "水文观测站", "雨水情监测站"},
                // 气压数据采集站
                {"气压观测站", "大气压力监测站", "气压数据采集点"},
                // 温度数据采集站
                {"温度湿度监测站", "气象温度站", "温湿度观测点"},
                // 辐射数据采集站
                {"太阳辐射监测站", "紫外线观测站", "辐射数据采集点"},
                // 风况数据采集站
                {"风速风向监测站", "风能观测站", "风况数据采集点"}
        };

        try (PreparedStatement selectStmt = conn.prepareStatement(selectDistrictsSql);
             PreparedStatement insertStmt = conn.prepareStatement(insertStationSql)) {

            conn.setAutoCommit(false);
            Random random = new Random();

            ResultSet districtRs = selectStmt.executeQuery();

            int stationId = 1;
            int batchSize = 50;
            int count = 0;

            while (districtRs.next()) {
                int districtId = districtRs.getInt("district_id");
                String districtName = districtRs.getString("district_name");
                double baseLongitude = districtRs.getDouble("longitude");
                double baseLatitude = districtRs.getDouble("latitude");

                System.out.println("正在生成地区 " + districtName + " 的详细采集站数据...");

                // 每种类型生成3个采集站
                for (int typeIndex = 0; typeIndex < STATION_TYPES.length; typeIndex++) {
                    String stationType = STATION_TYPES[typeIndex];

                    for (int i = 0; i < 3; i++) {
                        // 使用详细的采集站名称
                        String stationName = districtName + detailedStationNames[typeIndex][i];

                        // 生成更合理的经纬度偏移
                        double longitude = generateCoordinateOffset(baseLongitude, random, i);
                        double latitude = generateCoordinateOffset(baseLatitude, random, i);

                        // 设置插入参数
                        insertStmt.setInt(1, stationId);
                        insertStmt.setInt(2, districtId);
                        insertStmt.setString(3, stationName);
                        insertStmt.setDouble(4, longitude);
                        insertStmt.setDouble(5, latitude);
                        insertStmt.setString(6, stationType);

                        insertStmt.addBatch();
                        stationId++;
                        count++;

                        // 批量提交
                        if (count % batchSize == 0) {
                            insertStmt.executeBatch();
                            conn.commit();
                        }
                    }
                }
            }

            // 提交剩余数据
            insertStmt.executeBatch();
            conn.commit();

            System.out.println("详细采集站数据生成完成！共生成 " + count + " 个采集站。");

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 生成坐标偏移，使同一地区的采集站分布更合理
     */
    private static double generateCoordinateOffset(double baseCoordinate, Random random, int index) {
        // 根据索引生成不同的偏移模式，使站点分布更均匀
        double[] offsets = {-0.008, 0.005, 0.012}; // 三个站点的基本偏移
        double randomOffset = (random.nextDouble() - 0.5) * 0.004; // 小范围随机偏移

        return baseCoordinate + offsets[index % 3] + randomOffset;
    }

}